package com.nsi.controller.portal.nsi_post_bar;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nsi.common.Const;
import com.nsi.common.ServerResponse;
import com.nsi.enums.CheckStateEnum;
import com.nsi.pojo.PostCategory;
import com.nsi.pojo.PostCategoryItem;
import com.nsi.service.PostCategoryItemService;
import com.nsi.service.PostCategoryService;
import com.nsi.vo.nsi_shop_bar.PostCategoryItemVO;
import com.nsi.vo.nsi_shop_bar.PostInfoVO;
import com.nsi.vo.nsi_shop_bar.PostVO;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>`
 * 帖子类目表 前端控制器
 * </p>
 *
 * @author Luo Zhen
 * @since 2019-12-16
 */
@Controller
@RequestMapping("/post/")
@Api(value = "/post/", description = "新学说贴吧——(前台)贴吧类目")
public class PostCategoryController {

    @Autowired
    private PostCategoryService postCategoryService;
    @Autowired
    private PostCategoryItemService postCategoryItemService;

    /**
     * 返回首页信息(类目列表，帖子最新列表，最热门的帖子前6条)
     *
     * @return
     */
    @RequestMapping(value = "list.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "返回列表", httpMethod = "GET")
    public ServerResponse findPostCategoryList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                               @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey) {

        PostInfoVO postInfoVO = new PostInfoVO();

        // 返回类目信息
        List<PostVO> postVos = postCategoryService.findList();
        postInfoVO.setPostVOList(postVos);

        EntityWrapper<PostCategoryItem> wrapper = this.assembleWrapper(searchKey);
        // 返回最新帖子列表(分页)
        List<PostCategoryItem> lastItemList = postCategoryItemService.selectPage(
                new Page<>(pageNum, pageSize), wrapper
        ).getRecords();
        postInfoVO.setLastItemList(lastItemList);

        // 返回列表过滤条数
        lastItemList = postCategoryItemService.selectList(wrapper);
        postInfoVO.setLastListCount(lastItemList.size());


        // 取出观看数最高的6条数据
        List<PostCategoryItem> hotItemList = postCategoryItemService
                .selectList(this.assembleWrapper(null));
        lastItemList = hotItemList.stream()
                .sorted(Comparator.comparing(PostCategoryItem::getWatchNum).reversed())
                .limit(6)
                .collect(Collectors.toList());
        postInfoVO.setHotItemList(lastItemList);

        // 取出置顶数据
        lastItemList = hotItemList.stream()
                .filter(item -> Const.TOP_VALUE.equals(item.getIsTop()))
                .collect(Collectors.toList());
        postInfoVO.setTopItemList(lastItemList);


        return ServerResponse.createBySuccess(postInfoVO);
    }

    /**
     * 构造Wrapper
     *
     * @param search
     * @return
     */
    private EntityWrapper<PostCategoryItem> assembleWrapper(String search) {
        EntityWrapper<PostCategoryItem> wrapper = new EntityWrapper<>();
        wrapper.eq("is_check", CheckStateEnum.IN_APPROVE.getCode());
        if (StringUtils.isNotEmpty(search)) {
            wrapper.andNew()
                    .like("title", search).or()
                    .like("summary_desc", search).or()
                    .like("nick_name", search).or()
                    .like("post_type", search);
        }
        wrapper.orderBy("item_id", false);
        return wrapper;
    }

    /**
     * 智能搜索
     *
     * @return
     */
    @RequestMapping(value = "suggest_search.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "智能搜索", httpMethod = "GET")
    public ServerResponse suggestSearch(@RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey) {
        List<PostCategoryItem> postItem = postCategoryItemService.selectList(
                new EntityWrapper<PostCategoryItem>()
                        .setSqlSelect("title")
                        .eq("is_check", CheckStateEnum.IN_APPROVE.getCode())
                        .like(StringUtils.isNotBlank("searchKey"), "title", searchKey)
                        .orderBy("watch_num", false)
                        .last("limit 10")
        );
        List<String> titleList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(postItem)) {
            titleList = postItem.stream()
                    .map(item -> item.getTitle())
                    .collect(Collectors.toList());
        }
        return ServerResponse.createBySuccess(titleList);

    }


    /**
     * 返回最热列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "hot_list.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "返回最热列表", httpMethod = "GET")

    public ServerResponse findHotList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PostCategoryItem> postCategoryItems = postCategoryItemService.selectList(
                new EntityWrapper<PostCategoryItem>()
                        .eq("is_check", CheckStateEnum.IN_APPROVE.getCode())
                        .orderBy("watch_num", false)
        );
        PageInfo pageInfo = new PageInfo(postCategoryItems);
        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 返回贴吧详情和贴吧下所有的帖子
     *
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "detail.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id返回详情", httpMethod = "GET")
    public ServerResponse findPostCategoryItem(Integer categoryId,
                                               @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PostCategoryItemVO itemVO = new PostCategoryItemVO();
        // 返回类目id详情
        PostCategory posts = postCategoryService.selectById(categoryId);

        // 返回此类目id下的所有帖子
        List<PostCategoryItem> itemList = postCategoryItemService.selectPage(
                new Page(pageNum, pageSize),
                new EntityWrapper<PostCategoryItem>()
                        .eq("is_check", CheckStateEnum.IN_APPROVE.getCode()).and()
                        .like("post_type", posts.getCategoryName())
                        .orderBy("item_id", false)
        ).getRecords();

        BeanUtils.copyProperties(posts, itemVO);
        itemVO.setPostCategoryItems(itemList);

        // 返回满足条件帖子的总条数
        int result = postCategoryItemService.selectCount(
                new EntityWrapper<PostCategoryItem>()
                        .eq("is_check", CheckStateEnum.IN_APPROVE.getCode()).and()
                        .like("post_type", posts.getCategoryName())
                        .orderBy("item_id", false)
        );
        itemVO.setPostCategoryItemCount(result);

        return ServerResponse.createBySuccess(itemVO);
    }


}
